package service;

import common.Message;
import common.MessageType;
import utils.PrintUtil;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 处理消息的业务
 * @author 余一
 * @date 2021/10/31  14:47
 */
public class MessageService {
    /**
     * 私聊
     * @param msg 消息内容
     * @param sender 发送者
     * @param receiver 接收者
     */
    public void privateChat(String msg,String sender,String receiver){
        try {
            OutputStream outputStream = ThreadManager.getThread(sender).getSocket().getOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            Message message = new Message();
            message.setMesType(MessageType.MESSAGE_COMM_MES);
            message.setSender(sender);
            message.setGetter(receiver);
            message.setContent(msg);
            LocalDateTime localDateTime = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
            message.setSendTime(formatter.format(localDateTime));
            //发送给服务端
            System.out.println("用户【"+sender+"】向【" +receiver+ "】说："+msg);
            objectOutputStream.writeObject(message);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void massTexting(String content,String sender){
        try {
            OutputStream outputStream = ThreadManager.getThread(sender).getSocket().getOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            Message message = new Message();
            message.setMesType(MessageType.MESSAGE_TO_ALL);
            message.setSender(sender);
            message.setContent(content);
            LocalDateTime localDateTime = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
            message.setSendTime(formatter.format(localDateTime));
            //发送给服务端
            System.out.println("用户："+sender+"向所有人说："+content);
            objectOutputStream.writeObject(message);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
